<template>
  <a-row :gutter="[12, 0]" class="px-[12px] pt-2 a-row-box">
    <a-col :span="16" class="flex flex-col">
      <Card title="资金流概况" :desc="zjlgk.desc" class="h-full flex flex-col">
        <template #desc>
          <div class="flex flex-row">
            <a-select
              v-model:value="zjlgk.year"
              :options="utils.genSelectOptions('year')"
              @change="loadZjlgkData(false)"
              size="small"
            />
            <a-select
              class="ml-1"
              v-model:value="zjlgk.month"
              :options="utils.genSelectOptions('month')"
              @change="loadZjlgkData(false)"
              size="small"
            />
          </div>
        </template>

        <div class="grid grid-cols-4 gap-0 mt-4 cursor-pointer" @click="handleZjlgkClick()">
          <div class="text-center">
            <span class="text-md block">资金存款总额</span>
            <NumberAnimation
              class="text-2xl font-bold block"
              unit="亿元"
              :value="zjlgk.monthStatistics.capitalDepositTotal"
            />
          </div>
          <div class="text-center">
            <span class="text-md block">资金贷款总额</span>
            <NumberAnimation
              unit="亿元"
              class="text-2xl font-bold block"
              :value="zjlgk.monthStatistics.capitalLoanTotal"
            />
          </div>
          <div class="text-center">
            <span class="text-md block">个人消费贷款额</span>
            <NumberAnimation
              unit="亿元"
              class="text-2xl font-bold block"
              :value="zjlgk.monthStatistics.personalConsumptionLoan"
            />
          </div>
          <div class="text-center">
            <span class="text-md block">企业贷款额</span>
            <NumberAnimation
              unit="亿元"
              class="text-2xl font-bold block"
              :value="zjlgk.monthStatistics.enterpriseLoanAmount"
            />
          </div>
        </div>
        <div class="grid grid-cols-4 gap-0 cursor-pointer mt-4" @click="handleZjlgkClick()">
          <div class="text-center">
            <span class="text-md block">同比增幅</span>
            <span class="text-2xl font-bold block">
              <span class="valueNum-zf">
                {{
                  zjlgk.monthStatistics.capitalDepositTotalYoy > 0
                    ? '+' + zjlgk.monthStatistics.capitalDepositTotalYoy
                    : zjlgk.monthStatistics.capitalDepositTotalYoy
                }}
              </span>
              <span class="unit">{{
                zjlgk.monthStatistics.capitalDepositTotalYoy == '/' ? '' : '%'
              }}</span>
            </span>
          </div>
          <div class="text-center">
            <span class="text-md block">同比增幅</span>
            <span class="text-2xl font-bold block">
              <span class="valueNum-zf">
                {{
                  zjlgk.monthStatistics.capitalLoanTotalYoy > 0
                    ? '+' + zjlgk.monthStatistics.capitalLoanTotalYoy
                    : zjlgk.monthStatistics.capitalLoanTotalYoy
                }}
              </span>
              <span class="unit">{{
                zjlgk.monthStatistics.capitalLoanTotalYoy == '/' ? '' : '%'
              }}</span>
            </span>
          </div>
          <div class="text-center">
            <span class="text-md block">同比增幅</span>
            <span class="text-2xl font-bold block">
              <span class="valueNum-zf">
                {{
                  zjlgk.monthStatistics.personalConsumptionLoanYoy > 0
                    ? '+' + zjlgk.monthStatistics.personalConsumptionLoanYoy
                    : zjlgk.monthStatistics.personalConsumptionLoanYoy
                }}
              </span>
              <span class="unit">{{
                zjlgk.monthStatistics.personalConsumptionLoanYoy == '/' ? '' : '%'
              }}</span>
            </span>
          </div>
          <div class="text-center">
            <span class="text-md block">同比增幅</span>
            <span class="text-2xl font-bold block">
              <span class="valueNum-zf">
                {{
                  zjlgk.monthStatistics.enterpriseLoanAmountYoy > 0
                    ? '+' + zjlgk.monthStatistics.enterpriseLoanAmountYoy
                    : zjlgk.monthStatistics.enterpriseLoanAmountYoy
                }}
              </span>
              <span class="unit">{{
                zjlgk.monthStatistics.enterpriseLoanAmountYoy == '/' ? '' : '%'
              }}</span>
            </span>
          </div>
        </div>
      </Card>

      <a-row :gutter="[12, 0]" class="h-full mt-[12px]">
        <a-col :span="12" class="flex flex-col">
          <Card title="资金存款总额" :desc="zjckze.desc" class="h-full flex flex-col">
            <template #desc>
              <div class="flex flex-row">
                <a-select
                  v-model:value="zjckze.year"
                  :options="utils.genSelectOptions('year')"
                  @change="loadZjlckData(false)"
                  size="small"
                />
              </div>
            </template>
            <div
              id="zjckze"
              class="w-full h-full mx-auto cursor-pointer my-[12px]"
              @click="handleZjckzeClick"
            ></div>
          </Card>
        </a-col>

        <a-col :span="12" class="flex flex-col">
          <Card title="资金贷款总额" :desc="zjdkze.desc" class="h-full flex flex-col">
            <template #desc>
              <div class="flex flex-row">
                <a-select
                  v-model:value="zjdkze.year"
                  :options="utils.genSelectOptions('year')"
                  @change="loadZjdkzeData(false)"
                  size="small"
                />
              </div>
            </template>
            <div id="zjdkze" class="w-full h-full mx-auto my-[12px]"></div>
          </Card>
        </a-col>
      </a-row>

      <a-row :gutter="[12, 0]" class="h-full mt-[12px]">
        <a-col :span="12" class="flex flex-col">
          <Card title="个人消费贷款总额" :desc="grxdkze.desc" class="h-full flex flex-col">
            <template #desc>
              <div class="flex flex-row">
                <a-select
                  v-model:value="grxdkze.year"
                  :options="utils.genSelectOptions('year')"
                  @change="loadGrxflzeData(false)"
                  size="small"
                />
              </div>
            </template>
            <div id="grxflze" class="w-full h-full mx-auto my-[12px]"></div>
          </Card>
        </a-col>

        <a-col :span="12" class="flex flex-col">
          <Card title="企业贷款总额" :desc="qydkze.desc" class="h-full flex flex-col">
            <template #desc>
              <div class="flex flex-row">
                <a-select
                  v-model:value="qydkze.year"
                  :options="utils.genSelectOptions('year')"
                  @change="loadQydkzeData(false)"
                  size="small"
                />
              </div>
            </template>
            <div id="qyflze" class="w-full h-full mx-auto my-[12px]"></div>
          </Card>
        </a-col>
      </a-row>
    </a-col>

    <a-col :span="8" class="h-full flex flex-col">
      <Card title="资金流数据" :desc="zjlsj.desc" class="h-full flex flex-col">
        <template #desc>
          <div class="flex flex-row">
            <a-select
              v-model:value="zjlsj.year"
              :options="utils.genSelectOptions('year')"
              @change="loadZjlsjData(false)"
              size="small"
            />
            <a-select
              class="ml-1"
              v-model:value="zjlsj.month"
              :options="utils.genSelectOptions('month')"
              @change="loadZjlsjData(false)"
              size="small"
            />
          </div>
        </template>

        <div class="w-full flex flex-col" style="height: calc(100% - 12px)">
          <div id="ndcdb" class="w-full flex-1 mx-auto"></div>
          <div id="nddkywzb" class="w-full flex-1 mx-auto"></div>
        </div>

        <div
          v-if="false"
          class="flex flex-row mt-[12px] pb-[12px]"
          style="height: calc(100% - 200px - 12px)"
        >
          <div class="w-full h-full flex flex-col">
            <p class="text-[12px] font-bold mt-[22px] text-gray-300 text-center mb-[4px]">
              {{ zjlsj.year ? `${zjlsj.year - 1}-${zjlsj.year}年度` : '' }}资金流数据
              <span class="text-gray-400 text-[10px]">（单位：亿元）</span>
            </p>

            <!--              &lt;!&ndash; 设置表格容器的固定高度，并添加 overflow 属性 &ndash;&gt;
              <div class="custom-table w-full h-full mt-[12px] mb-[12px] flex flex-col relative">
                &lt;!&ndash; 表头 &ndash;&gt;
                <div class="custom-table-header sticky top-0 z-10">
                  <div class="custom-table-cell">时间</div>
                  <div class="custom-table-cell">资金存款总额</div>
                  <div class="custom-table-cell">资金贷款总额</div>
                  <div class="custom-table-cell">存贷比(%)</div>
                  <div class="custom-table-cell">个人消费贷款额</div>
                  <div class="custom-table-cell">企业贷款额</div>
                  <div class="w-[9px] border-none"></div>
                </div>

                &lt;!&ndash; 表格内容 &ndash;&gt;
                <div class="custom-table-body flex-1 overflow-y-auto no-scrollbar">
                  <div v-for="(item, index) in gasRankingData" :key="index" class="custom-table-row">
                    <div class="custom-table-cell">{{ item.year + '年' + item.month + '月' }}</div>
                    <div class="custom-table-cell">{{ item.capitalDepositTotal }}</div>
                    <div class="custom-table-cell">{{ item.capitalLoanTotal }}</div>
                    <div class="custom-table-cell"
                      :class="item.depositAndThan > 0 ? 'text-green-500' : 'text-red-500'">
                      {{ item.depositAndThan }}%
                    </div>
                    <div class="custom-table-cell">{{ item.personalConsumptionLoan }}</div>
                    <div class="custom-table-cell">{{ item.enterpriseLoanAmount }}</div>
                  </div>
                </div>

                <div class="absolute bottom-0 left-0 right-0 h-[60px]" style="
                    background: linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5));
                  "></div>
              </div>-->
          </div>
        </div>
      </Card>
    </a-col>
  </a-row>
  <!-- 资金流概况 -->
  <ZjlgkModal ref="zjlgkModalRef" />
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import Card from './card.vue'
import * as echarts from 'echarts'
import { Apis } from '@/api'
import * as utils from '../utils'
import { useBigScreenStore } from '../store'
import NumberAnimation from '@/components/number-animation.vue'
import ZjlgkModal from '../modal/financial/zjlgk-modal.vue'
const emit = defineEmits(['mounted'])
const zjlgkModalRef = ref<InstanceType<typeof ZjlgkModal>>()
const bigScreenStore = useBigScreenStore()
/** 资金流概况 */
const zjlgk = reactive({
  desc: '',
  year: '',
  month: '',
  monthStatistics: {
    qnCapitalDepositTotal: 0, // 去年资金存款总额
    capitalDepositTotal: 0, // 资金存款总额
    qnCapitalLoanTotal: 0, // 去年资金贷款总额
    capitalLoanTotal: 0, // 资金贷款总额
    month: undefined, // 月份
    year: undefined, // 年份
    depositAndThan: 0, // 存贷比(%)
    qnDepositAndThan: 0, // 去年存贷比(%)
    personalConsumptionLoan: 0, // 个人消费贷款额
    qnPersonalConsumptionLoan: 0, // 去年个人消费贷款额
    enterpriseLoanAmount: 0, // 企业贷款额
    qnEnterpriseLoanAmount: 0, // 去年企业贷款额

    depositYoy: 0, // 资金存款总额同比增长率
    loanYoy: 0, // 资金贷款总额同比增长率
    personalLoanYoy: 0, // 个人消费贷款额同比增长率
    enterpriseLoanYoy: 0, // 企业贷款额同比增长率
  },
})

/** 资金存款总额 */
const zjckze = reactive({
  desc: '',
  year: '',
})

/** 资金存款总额 */
const zjckzeOptions = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '0%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: ['2024年', '2023年'],
  },
  xAxis: {
    type: 'category',
    data: utils.genMonthArray(),
    axisLabel: {
      fontSize: 12,
    },
  },
  yAxis: {
    type: 'value',
    name: '亿元',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  grid: {
    top: '18%',
    left: '6%',
    right: '6%',
    bottom: '15%',
    containLabel: true,
  },
  series: [],
})

/** 资金贷款总额 */
const zjdkze = reactive({
  desc: '',
  year: '',
})

/** 资金贷款总额 */
const zjdkzeOptions = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '0%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: ['2024年', '2023年'],
  },
  xAxis: {
    type: 'category',
    data: utils.genMonthArray(),
    axisLabel: {
      fontSize: 12,
    },
  },
  yAxis: {
    type: 'value',
    name: '亿元',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  grid: {
    top: '18%',
    left: '6%',
    right: '6%',
    bottom: '15%',
    containLabel: true,
  },
  series: [],
})

/** 个人消费贷款总额 */
const grxdkze = reactive({
  desc: '',
  year: '',
})

/** 个人消费贷款总额 */
const grxflzeOptions = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '0%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: ['2024年', '2023年'],
  },
  xAxis: {
    type: 'category',
    data: utils.genMonthArray(),
    axisLabel: {
      fontSize: 12,
    },
  },
  yAxis: {
    type: 'value',
    name: '亿元',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  grid: {
    top: '18%',
    left: '6%',
    right: '6%',
    bottom: '15%',
    containLabel: true,
  },
  series: [],
})

/** 企业贷款总额 */
const qydkze = reactive({
  desc: '截止2024年12月',
  year: '',
})

/** 企业贷款总额 */
const qyflzeOptions = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '0%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: ['2024年', '2023年'],
  },
  xAxis: {
    type: 'category',
    data: utils.genMonthArray(),
    axisLabel: {
      fontSize: 12,
    },
  },
  yAxis: {
    type: 'value',
    name: '亿元',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  grid: {
    top: '18%',
    left: '6%',
    right: '6%',
    bottom: '15%',
    containLabel: true,
  },
  series: [],
})

/** 资金流数据 */
const zjlsj = reactive({
  desc: '',
  year: '',
  month: '',
  monthStatistics: {},
})

/** 年度存贷比 */
const ndcdbOptions = reactive({
  title: {
    text: '月度存贷比',
    left: 'center',
    top: '15%',
    textStyle: {
      fontSize: 16,
    },
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
    borderColor: 'rgba(255,255,255,0.3)',
    textStyle: {
      // color: '#fff',
      fontSize: 14,
    },
  },
  legend: {
    show: true,
    orient: 'horizontal',
    data: ['存款总额', '贷款总额'],
    bottom: '5%',
    itemGap: 3, // 减小图例间距
    itemWidth: 10, // 减小图例标记的宽度
    itemHeight: 10, // 减小图例标记的高度
    textStyle: {
      fontSize: 12, // 减小图例文字大小
    },
    formatter: function (name) {
      const data = [
        { name: '存款总额', total: zjlsj.monthStatistics?.capitalDepositTotal || 0 },
        { name: '贷款总额', total: zjlsj.monthStatistics?.capitalLoanTotal || 0 },
      ]
      const item = data.find((d) => d.name === name)
      if (!item) return name
      const total = data.reduce((sum, cur) => sum + cur.total, 0)
      const percentage = ((item.total / total) * 100).toFixed(1)
      return `${name} ${isNaN(percentage) ? '0' : percentage}%`
    },
  },
  series: [
    {
      name: '存贷比',
      type: 'pie',
      radius: '40%',
      data: [],
      label: {
        show: false,
        formatter: function (params) {
          // 格式化标签为：序号. 名称 (值)
          return `${params.name} (${params.value})`
        },
        // color: '#ffffff', // 设置字体颜色为白色
      },
      labelLine: {
        show: false,
        length: 2, // 第一段指示线长度
        length2: 2, // 第二段指示线长度
        smooth: true, // 指示线平滑
      },
      color: ['#4282ff', '#37e0cc'],
    },
  ],
})

/** 年度贷款业务占比 */
const nddkywzbOptions = reactive({
  title: {
    text: '月度贷款业务占比',
    left: 'center',
    top: '15%',
    textStyle: {
      fontSize: 16,
    },
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
    borderColor: 'rgba(255,255,255,0.3)',
    textStyle: {
      // color: '#fff',
      fontSize: 14,
    },
  },
  legend: {
    show: true,
    orient: 'horizontal',
    data: ['个人消费贷款', '企业贷款'],
    bottom: '5%',
    itemGap: 3, // 减小图例间距
    itemWidth: 10, // 减小图例标记的宽度
    itemHeight: 10, // 减小图例标记的高度
    textStyle: {
      fontSize: 12, // 减小图例文字大小
    },
    formatter: function (name) {
      const data = [
        { name: '个人消费贷款', total: zjlsj.monthStatistics?.personalConsumptionLoan || 0 },
        { name: '企业贷款', total: zjlsj.monthStatistics?.enterpriseLoanAmount || 0 },
      ]
      const item = data.find((d) => d.name === name)
      if (!item) return ''
      const index = data.indexOf(item) + 1
      const total = data.reduce((sum, cur) => sum + cur.total, 0)
      const percentage = ((item.total / total) * 100).toFixed(1)
      return `${name} ${isNaN(percentage) ? '0' : percentage}%`
    },
  },
  series: [
    {
      name: '贷款业务占比',
      type: 'pie',
      radius: '40%',
      data: [],
      label: {
        show: false,
        formatter: function (params) {
          // 格式化标签为：序号. 名称 (值)
          return `${params.name} (${params.value})`
        },
        // color: '#ffffff', // 设置字体颜色为白色
      },
      labelLine: {
        show: false,
        length: 2, // 第一段指示线长度
        length2: 2, // 第二段指示线长度
        smooth: true, // 指示线平滑
      },
      color: ['#4282ff', '#37e0cc'],
    },
  ],
})

const gasRankingData = ref<any[]>([])

/** 资金存款总额 */
function initZjckzeChart() {
  const chartDom = document.getElementById('zjckze')
  if (!chartDom) {
    return
  }
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(zjckzeOptions, { notMerge: true })
}

/** 资金贷款总额 */
function initZjdkzeChart() {
  const chartDom = document.getElementById('zjdkze')
  if (!chartDom) {
    return
  }
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(zjdkzeOptions, { notMerge: true })
}

/** 个人消费贷款总额 */
function initGrxflzeChart() {
  const chartDom = document.getElementById('grxflze')
  if (!chartDom) {
    return
  }
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(grxflzeOptions, { notMerge: true })
}

/** 企业贷款总额 */
function initQyflzeChart() {
  const chartDom = document.getElementById('qyflze')
  if (!chartDom) {
    return
  }
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(qyflzeOptions, { notMerge: true })
}

/** 年度存贷比 */
function initNdcdbChart() {
  const chartDom = document.getElementById('ndcdb')
  if (!chartDom) {
    return
  }
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(ndcdbOptions, { notMerge: true })
}

/** 年度贷款业务占比 */
function initNddkywzbChart() {
  const chartDom = document.getElementById('nddkywzb')
  if (!chartDom) {
    return
  }
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }
  myChart.setOption(nddkywzbOptions, { notMerge: true })
}

/** 资金流数据 */
async function loadZjlgkData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }

  try {
    let year, month
    if (zjlgk.year && zjlgk.month) {
      year = zjlgk.year
      month = zjlgk.month
    } else {
      const getNewestDataRes = await Apis.szbt.capitalFlowData.get_getNewestData()
      ;({ year, month } = utils.parseDate(getNewestDataRes.newestDate))
    }

    zjlgk.year = year.toString()
    zjlgk.month = month.toString()

    const getChartDataRes = await Apis.szbt.capitalFlowData.get_getChartData({
      params: {
        year: year,
        month: month,
      },
    })

    zjlgk.monthStatistics = getChartDataRes.monthStatistics

    // 计算同比去年
    zjlgk.monthStatistics.capitalDepositTotalYoy = utils.calcYoy(
      zjlgk.monthStatistics.capitalDepositTotal,
      zjlgk.monthStatistics.qnCapitalDepositTotal,
    )

    zjlgk.monthStatistics.capitalLoanTotalYoy = utils.calcYoy(
      zjlgk.monthStatistics.capitalLoanTotal,
      zjlgk.monthStatistics.qnCapitalLoanTotal,
    )

    zjlgk.monthStatistics.personalConsumptionLoanYoy = utils.calcYoy(
      zjlgk.monthStatistics.personalConsumptionLoan,
      zjlgk.monthStatistics.qnPersonalConsumptionLoan,
    )

    zjlgk.monthStatistics.enterpriseLoanAmountYoy = utils.calcYoy(
      zjlgk.monthStatistics.enterpriseLoanAmount,
      zjlgk.monthStatistics.qnEnterpriseLoanAmount,
    )
  } catch (error) {
    throw error
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

/** 资金存款总额 */
async function loadZjlckData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }

  try {
    let year
    if (zjckze.year) {
      year = zjckze.year
    } else {
      const getNewestDataRes = await Apis.szbt.capitalFlowData.get_getNewestData()
      ;({ year } = utils.parseDate(getNewestDataRes.newestDate))
    }

    zjckze.year = year.toString()

    const getChartDataRes = await Apis.szbt.capitalFlowData.get_getChartData({
      params: {
        year: year,
        month: 12,
      },
    })

    const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')

    zjckzeOptions.legend.data = sortedKeys.map((item) => `${item}年`)
    const series: any[] = []
    Object.keys(groupedData).forEach((year, index) => {
      series.push({
        name: `${year}年`,
        type: 'line',
        radius: '100%',
        smooth: true,
        symbolSize: 2,
        lineStyle: {
          width: 2,
        },
        color: utils.genColors()[index],
        data: groupedData[year].map((item) => {
          return {
            value: item.capitalDepositTotal,
            name: item.month + '月',
          }
        }),
      })
    })
    zjckzeOptions.series = series

    initZjckzeChart()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

/** 资金贷款总额 */
async function loadZjdkzeData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }

  try {
    let year
    if (zjdkze.year) {
      year = zjdkze.year
    } else {
      const getNewestDataRes = await Apis.szbt.capitalFlowData.get_getNewestData()
      ;({ year } = utils.parseDate(getNewestDataRes.newestDate))
    }

    zjdkze.year = year.toString()

    const getChartDataRes = await Apis.szbt.capitalFlowData.get_getChartData({
      params: {
        year: year,
        month: 12,
      },
    })

    const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')

    zjdkzeOptions.legend.data = sortedKeys.map((item) => `${item}年`)
    const series: any[] = []
    Object.keys(groupedData).forEach((year, index) => {
      series.push({
        name: `${year}年`,
        type: 'line',
        radius: '100%',
        smooth: true,
        symbolSize: 2,
        lineStyle: {
          width: 2,
        },
        color: utils.genColors()[index],
        data: groupedData[year].map((item) => {
          return {
            value: item.capitalLoanTotal,
            name: item.month + '月',
          }
        }),
      })
    })
    zjdkzeOptions.series = series

    initZjdkzeChart()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

/** 个人消费贷款总额 */
async function loadGrxflzeData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }

  try {
    let year
    if (grxdkze.year) {
      year = grxdkze.year
    } else {
      const getNewestDataRes = await Apis.szbt.capitalFlowData.get_getNewestData()
      ;({ year } = utils.parseDate(getNewestDataRes.newestDate))
    }

    grxdkze.year = year.toString()

    const getChartDataRes = await Apis.szbt.capitalFlowData.get_getChartData({
      params: {
        year: year,
        month: 12,
      },
    })

    const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')

    grxflzeOptions.legend.data = sortedKeys.map((item) => `${item}年`)
    const series: any[] = []
    Object.keys(groupedData).forEach((year, index) => {
      series.push({
        name: `${year}年`,
        type: 'line',
        radius: '100%',
        smooth: true,
        symbolSize: 2,
        lineStyle: {
          width: 2,
        },
        color: utils.genColors()[index],
        data: groupedData[year].map((item) => {
          return {
            value: item.personalConsumptionLoan,
            name: item.month + '月',
          }
        }),
      })
    })
    grxflzeOptions.series = series

    initGrxflzeChart()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

/** 企业贷款总额 */
async function loadQydkzeData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }
  try {
    let year
    if (qydkze.year) {
      year = qydkze.year
    } else {
      const getNewestDataRes = await Apis.szbt.capitalFlowData.get_getNewestData()
      ;({ year } = utils.parseDate(getNewestDataRes.newestDate))
    }

    qydkze.year = year.toString()

    const getChartDataRes = await Apis.szbt.capitalFlowData.get_getChartData({
      params: {
        year: year,
        month: 12,
      },
    })

    const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')

    qyflzeOptions.legend.data = sortedKeys.map((item) => `${item}年`)
    const series: any[] = []
    Object.keys(groupedData).forEach((year, index) => {
      series.push({
        name: `${year}年`,
        type: 'line',
        radius: '100%',
        smooth: true,
        symbolSize: 2,
        lineStyle: {
          width: 2,
        },
        color: utils.genColors()[index],
        data: groupedData[year].map((item) => {
          return {
            value: item.enterpriseLoanAmount,
            name: item.month + '月',
          }
        }),
      })
    })
    qyflzeOptions.series = series

    initQyflzeChart()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

/** 资金流数据 */
async function loadZjlsjData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }

  try {
    let year, month
    if (zjlsj.year && zjlsj.month) {
      year = zjlsj.year
      month = zjlsj.month
    } else {
      const getNewestDataRes = await Apis.szbt.capitalFlowData.get_getNewestData()
      ;({ year, month } = utils.parseDate(getNewestDataRes.newestDate))
    }

    zjlsj.year = year.toString()
    zjlsj.month = month.toString()

    const getChartDataRes = await Apis.szbt.capitalFlowData.get_getChartData({
      params: {
        year: year,
        month: month,
      },
    })

    zjlsj.monthStatistics = getChartDataRes.monthStatistics

    // debugger
    // 月度存贷比
    ndcdbOptions.series[0].data = [
      { value: getChartDataRes.monthStatistics?.capitalDepositTotal || 0, name: '存款总额' },
      { value: getChartDataRes.monthStatistics?.capitalLoanTotal || 0, name: '贷款总额' },
    ]

    // 月度贷款业务占比
    nddkywzbOptions.series[0].data = [
      {
        value: getChartDataRes.monthStatistics?.personalConsumptionLoan || 0,
        name: '个人消费贷款',
      },
      { value: getChartDataRes.monthStatistics?.enterpriseLoanAmount || 0, name: '企业贷款' },
    ]

    initNdcdbChart()
    initNddkywzbChart()

    gasRankingData.value = getChartDataRes.months.sort((a, b) => {
      // 先按年份降序
      if (b.year !== a.year) {
        return b.year - a.year
      }
      // 年份相同时按月份降序
      return b.month - a.month
    })
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

async function loadData() {
  bigScreenStore.showLoading()

  try {
    await Promise.all([
      loadZjlgkData(),
      loadZjlckData(),
      loadZjdkzeData(),
      loadGrxflzeData(),
      loadQydkzeData(),
      loadZjlsjData(),
    ])
  } catch (error) {
  } finally {
    bigScreenStore.hideLoading()
  }
}

function handleZjlgkClick() {
  zjlgkModalRef.value?.setData({
    params: {
      year: zjlgk.year,
    },
  })
  zjlgkModalRef.value?.open()
}

onMounted(async () => {
  await loadData()
  emit('mounted')
})
</script>

<style scoped>
div {
  box-sizing: border-box;
}

.no-scrollbar::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条（适用于 Webkit 浏览器，例如 Chrome、Safari） */
}

.no-scrollbar {
  /* 滚动条整体部分 */
  &::-webkit-scrollbar {
    width: 4px;
    height: 4px;
    background: transparent;
  }

  /* 滚动条滑块 */
  &::-webkit-scrollbar-thumb {
    border-radius: 2px;
    background: linear-gradient(180deg, #00c6fb 0%, #0a2f57 100%);
    box-shadow: inset 0 0 6px rgba(0, 198, 251, 0.3);
  }

  /* 滚动条轨道 */
  &::-webkit-scrollbar-track {
    border-radius: 2px;
    background: rgba(0, 91, 234, 0.1);
  }

  /* 兼容 Firefox */
  scrollbar-width: thin;
  scrollbar-color: #0a2f57 transparent;
}

/* 表格容器 */
.custom-table {
  display: flex;
  flex-direction: column;
  border: 1px solid #aaa;
  /* 边框颜色：灰色 */
  border-radius: 4px;
  /* 圆角 */
  overflow: hidden;
  /* 防止内容溢出 */
  /* background-color: #ffffff; */
  /* 白色背景 */
}

/* 表头样式 */
.custom-table-header {
  display: flex;
  /* background-color: #f3f4f6; */
  /* 浅灰背景 */
  font-weight: bold;
  border-bottom: 1px solid #aaa;
  /* 表头底部边框 */
  font-size: 12px;
}

/* 表行样式 */
.custom-table-row {
  display: flex;
  border-bottom: 1px solid #aaa;
  /* 行的底部边框 */
  transition: background-color 0.2s;
  /* 悬浮时的过渡效果 */
}

.custom-table-row:last-child {
  border-bottom: none;
  /* 最后一行没有边框 */
}

/* 单元格样式 */
.custom-table-cell {
  flex: 1;
  text-align: center;
  color: #eee;
  height: 40px;
  border-right: 1px solid #aaa;
  /* 单元格分隔线 */
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  white-space: nowrap;
  /* 防止文字换行 */
  overflow: hidden;
  /* 超出部分隐藏 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
  font-size: 12px;
}

.custom-table-cell:last-child {
  border-right: none;
  /* 最后一列没有分隔线 */
}

/* 行悬浮效果 */

.custom-table-row:hover {
  /* background-color: #f9fafb; */
  /* 悬浮时背景变浅灰 */
}

/* 表头悬浮效果 */
.custom-table-header .custom-table-cell {
  /* background-color: #e5e7eb; */
  /* 表头固定时背景色 */
  font-size: 12px;
  /* 表头文字大小 */
}
.text-md {
  color: #999;
}
.unit {
  font-size: 12px;
  color: #999999;
  margin-left: 5px;
}
.valueNum-zf {
  color: #00bcc3;
}
.a-row-box {
  min-height: calc(100vh - 220px) !important;
}
</style>
